package com.guli.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.product.dao.CategoryDao;
import com.guli.gulimall.product.entity.CategoryEntity;
import com.guli.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> treeList() {
        //先访问一遍数据库，拿到所有数据
        List<CategoryEntity> allList = baseMapper.selectList(null);
        //以流的方式过滤
        List<CategoryEntity> treeList = allList.stream().filter(item -> {
            //过滤出第一级列表
            return item.getParentCid().equals(0L);
            //将流组合成map
        }).map(item -> {
            //获取当前元素的子列表
            List<CategoryEntity> children = findChildren(allList,item);
            //将子列表放入元素
            item.setChildren(children);
            return item;
            }
            //将流以集合返回
        ).sorted((s1,s2) -> {
            return (s1.getSort()==null?0:s1.getSort()) - (s2.getSort()==null?0:s2.getSort());
        }).collect(Collectors.toList());
        //获取到树形列表
        return treeList;
    }

    private List<CategoryEntity> findChildren(List<CategoryEntity> allList, CategoryEntity category) {
        List<CategoryEntity> list =  allList.stream().filter(item -> {
            //过滤出子列表
            return item.getParentCid().equals(category.getCatId());
        }).map(item -> {
            //获取当前元素的子列表
            List<CategoryEntity> children = findChildren(allList, item);
            //将子列表放入元素
            item.setChildren(children);
            return item;
            //将流以集合返回
        }).sorted((s1,s2) -> {
            return (s1.getSort()==null?0:s1.getSort()) - (s2.getSort()==null?0:s2.getSort());
        }).collect(Collectors.toList());
        //返回子列表
        return list;
    }
}
